﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using LeadThing.AbpZeroTemplate.LawsRegulationses.Authorization;
using LeadThing.AbpZeroTemplate.LawsRegulationses.Dtos;
using LeadThing.AbpZeroTemplate.Dto;
using LeadThing.AbpZeroTemplate.Files;
using static LeadThing.AbpZeroTemplate.Configuration.AppSettings;

namespace LeadThing.AbpZeroTemplate.LawsRegulationses
{
    /// <summary>
    /// 法律法规表服务实现
    /// </summary>



    public class LawsRegulationsAppService : AbpZeroTemplateAppServiceBase, ILawsRegulationsAppService
    {
        private readonly IRepository<LawsRegulations, long> _lawsRegulationsRepository;
        private readonly IRepository<File, long> _fileRepository;
        private readonly ILawsRegulationsListExcelExporter _lawsRegulationsListExcelExporter;
        private readonly ISqlExecuter _sqlExecuter;//sql语句接口


        private readonly LawsRegulationsManage _lawsRegulationsManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public LawsRegulationsAppService(IRepository<LawsRegulations, long> lawsRegulationsRepository,
LawsRegulationsManage lawsRegulationsManage
      , ILawsRegulationsListExcelExporter lawsRegulationsListExcelExporter
      , ISqlExecuter sqlExecuter
      , IRepository<File, long> fileRepository
  )
        {
            _lawsRegulationsRepository = lawsRegulationsRepository;
            _lawsRegulationsManage = lawsRegulationsManage;
            _lawsRegulationsListExcelExporter = lawsRegulationsListExcelExporter;
            _sqlExecuter = sqlExecuter;
            _fileRepository = fileRepository;
        }


        #region 实体的自定义扩展方法
        private IQueryable<LawsRegulations> _lawsRegulationsRepositoryAsNoTrack => _lawsRegulationsRepository.GetAll().AsNoTracking();

        /// <summary>
        /// 获取全部法律法规数据加载页面数据
        /// </summary>
        /// <returns></returns>
        public List<LawsRegulationsLoadPageDto> GetAllLawsRegulationsLoadPage(GetLawsRegulationsInput input)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(" select ");

            if (input.Top > 0)
            {
                sb.Append(" top ");
                sb.Append(input.Top);
            }

            sb.Append("  * from Basic.LawsRegulations where isDeleted=0 ");

            if (!string.IsNullOrWhiteSpace(input.Filter))
            {
                sb.Append(" and Title like '%");
                sb.Append(input.Filter);
                sb.Append("%'");
            }

            return _sqlExecuter.SqlQuery<LawsRegulationsLoadPageDto>(sb.ToString()).ToList();
        }

        #endregion


        #region 法律法规表管理

        /// <summary>
        /// 根据查询条件获取法律法规表分页列表
        /// </summary>
        [AbpAuthorize(LawsRegulationsAppPermissions.LawsRegulations)]
        public async Task<PagedResultDto<LawsRegulationsListDto>> GetPagedLawsRegulationssAsync(GetLawsRegulationsInput input)
        {

            var query = _lawsRegulationsRepositoryAsNoTrack;

            #region 根据传入的参数添加过滤条件

            //TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrWhiteSpace(input.Filter))
                query = query.Where(p => p.Title.Contains(input.Filter));

            #endregion

            var lawsRegulationsCount = await query.CountAsync();

            var lawsRegulationss = await query
            .OrderByDescending(p => p.Id)
            .PageBy(input)
            .ToListAsync();

            var lawsRegulationsListDtos = lawsRegulationss.MapTo<List<LawsRegulationsListDto>>();
            return new PagedResultDto<LawsRegulationsListDto>(
            lawsRegulationsCount,
            lawsRegulationsListDtos
            );
        }

        /// <summary>
        /// 通过Id获取法律法规表信息进行编辑或修改 
        /// </summary>
        [AbpAuthorize(LawsRegulationsAppPermissions.LawsRegulations)]
        public async Task<GetLawsRegulationsForEditOutput> GetLawsRegulationsForEditAsync(NullableIdDto<long> input)
        {
            var output = new GetLawsRegulationsForEditOutput();

            LawsRegulationsEditDto lawsRegulationsEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _lawsRegulationsRepository.GetAsync(input.Id.Value);
                lawsRegulationsEditDto = entity.MapTo<LawsRegulationsEditDto>();
            }
            else
            {
                lawsRegulationsEditDto = new LawsRegulationsEditDto();
            }

            output.LawsRegulations = lawsRegulationsEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取法律法规表ListDto信息
        /// </summary>
        [AbpAuthorize(LawsRegulationsAppPermissions.LawsRegulations)]
        public async Task<LawsRegulationsListDto> GetLawsRegulationsByIdAsync(EntityDto<long> input)
        {
            var entity = await _lawsRegulationsRepository.GetAsync(input.Id);

            return entity.MapTo<LawsRegulationsListDto>();
        }







        /// <summary>
        /// 新增或更改法律法规表
        /// </summary>
        [AbpAuthorize(LawsRegulationsAppPermissions.LawsRegulations)]
        public async Task CreateOrUpdateLawsRegulationsAsync(CreateOrUpdateLawsRegulationsInput input)
        {
            if (input.LawsRegulationsEditDto.Id.HasValue)
            {
                await UpdateLawsRegulationsAsync(input.LawsRegulationsEditDto);
            }
            else
            {
                await CreateLawsRegulationsAsync(input.LawsRegulationsEditDto);
            }
        }

        /// <summary>
        /// 新增法律法规表
        /// </summary>
        [AbpAuthorize(LawsRegulationsAppPermissions.LawsRegulations_CreateLawsRegulations)]
        public virtual async Task<LawsRegulationsEditDto> CreateLawsRegulationsAsync(LawsRegulationsEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<LawsRegulations>();

            entity = await _lawsRegulationsRepository.InsertAsync(entity);
            return entity.MapTo<LawsRegulationsEditDto>();
        }

        /// <summary>
        /// 编辑法律法规表
        /// </summary>
        [AbpAuthorize(LawsRegulationsAppPermissions.LawsRegulations_EditLawsRegulations)]
        public virtual async Task UpdateLawsRegulationsAsync(LawsRegulationsEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _lawsRegulationsRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _lawsRegulationsRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除法律法规表
        /// </summary>
        [AbpAuthorize(LawsRegulationsAppPermissions.LawsRegulations_DeleteLawsRegulations)]
        public async Task DeleteLawsRegulationsAsync(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _lawsRegulationsRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除法律法规表
        /// </summary>
        [AbpAuthorize(LawsRegulationsAppPermissions.LawsRegulations_DeleteLawsRegulations)]
        public async Task BatchDeleteLawsRegulationsAsync(List<long> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _lawsRegulationsRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion

        #region 法律法规表的Excel导出功能


        public async Task<FileDto> GetLawsRegulationsToExcel()
        {
            var entities = await _lawsRegulationsRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<LawsRegulationsListDto>>();

            var fileDto = _lawsRegulationsListExcelExporter.ExportLawsRegulationsToFile(dtos);



            return fileDto;
        }


        #endregion

        #region APP接口

        /// <summary>
        /// 根据查询条件获取法律法规表分页列表
        /// </summary>
        public async Task<PagedResultDto<LawsRegulationsAPPListDto>> GetPagedLawsRegulationssAPPAsync(GetLawsRegulationsAPPInput input)
        {
            var _pageIndex = Convert.ToInt32(input.PageIndex);
            var _pageSize = Convert.ToInt32(input.PageSize);
            var query = _lawsRegulationsRepositoryAsNoTrack;

            var lawsRegulationsCount = await query.CountAsync();

            var lawsRegulationss = await query
            .OrderByDescending(p => p.Id)
            .Take(_pageSize * _pageIndex).Skip(_pageSize * (_pageIndex - 1))
            .ToListAsync();

            //var lawsRegulationsListDtos = lawsRegulationss.MapTo<List<LawsRegulationsAPPListDto>>();
            var fileList = _fileRepository.GetAll();

            return new PagedResultDto<LawsRegulationsAPPListDto>(
            lawsRegulationsCount,
            lawsRegulationss.Select(item =>
            {
                var dto = item.MapTo<LawsRegulationsAPPListDto>();
                var fileModel = fileList.Where(p => p.Id == dto.FileID).FirstOrDefault();
                if (fileModel != null)
                    dto.ImgUrl = AppSetting.AppUrl + fileModel.Url;

                return dto;
            }).ToList()
            );
        }

        /// <summary>
        /// 通过Id获取法律法规表信息进行编辑或修改 
        /// </summary>
        public async Task<LawsRegulationsAPPEditDto> GetLawsRegulationsForEditAPPAsync(EntityDto<string> input)
        {
            LawsRegulationsAPPEditDto lawsRegulationsEditDto;

            if (!string.IsNullOrWhiteSpace(input.Id))
            {
                var id = Convert.ToInt32(input.Id);
                var entity = await _lawsRegulationsRepository.GetAsync(id);
                lawsRegulationsEditDto = entity.MapTo<LawsRegulationsAPPEditDto>();

                var fileModel = _fileRepository.GetAll().Where(p => p.Id == lawsRegulationsEditDto.FileID).FirstOrDefault();
                if (fileModel != null)
                    lawsRegulationsEditDto.ImgUrl = AppSetting.AppUrl + fileModel.Url;
            }
            else
            {
                lawsRegulationsEditDto = new LawsRegulationsAPPEditDto();
            }

            return lawsRegulationsEditDto;
        }

        #endregion

    }
}
